using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Reflection;
using System.Web;

using GrailTechnology.AutoTags.DataType;
using GrailTechnology.AutoTags.Providers;

using log4net;

using Newtonsoft.Json;

namespace GrailTechnology.AutoTags.Library
{
    public class Base
    {
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public static string GetTags(int id)
        {
            HttpRequest request = HttpContext.Current.Request;

            log.Debug("Getting tags for node: " + id);

            var keys = new List<string>();
            
            // Problem using POST verb when using MNTP on same doctype
            NameValueCollection content = request.RequestType.ToLowerInvariant() == "post"
                                              ? request.Form
                                              : request.QueryString;

            foreach (string key in content)
            {
                if ((!key.StartsWith("_")) && (!key.ToLower().Contains("tag")))
                {
                    keys.Add(key);
                    log.Debug("form: " + key + " - " + content[key]);
                }
            }

            string text = Helper.Instance.GetFormProperties(content, keys); // To get data from form rather than node properties
            log.Debug("Using text: " + text);


            HttpContext.Current.Response.ContentType = "application/json";

            ITagProvider s = Config.Instance.GetProvider();
            if (Config.Instance.ProxyDomain.Length > 0)
            {
                s.Proxy = new WebProxy
                {
                    Credentials = new NetworkCredential(
                        Config.Instance.ProxyUsername,
                        Config.Instance.ProxyPassword,
                        Config.Instance.ProxyDomain)
                };
            }

            try
            {
                string[] tags = s.GenerateTags(text);
                Array.Sort(tags);
                var result = new { items = tags, autoAdd = Config.Instance.SelectTagsAutomatically };

                return JsonConvert.SerializeObject(result);
            }
            catch (Exception ex)
            {
                log.Fatal(ex);
                return JsonConvert.SerializeObject(new { error = ex.Message });
            }
        }
    }
}